package com.cypher.encryptionanddecryption.util;

import org.apache.commons.lang3.StringUtils;

/**
 * 协议工具类
 * @author: 古霸天
 * @date: 2020/11/20
 */
public class ProtocolUtils {

    /**
     * 起始码
     */
    public static final String con188Star = "68";
    /**
     * 终止码
     */
    public static final String con188End = "16";

    /**
     * 明文
     */
    public static final int CON_01 = 1;
    /**
     * 明文 + MAC
     */
    public static final int CON_02 = 2;
    /**
     * 密文
     */
    public static final int CON_03 = 3;
    /**
     * 密文 + MAC
     */
    public static final int CON_04 = 4;

    /**
     * 验证数据是否合法
     * @param bytes
     * @return
     *  合法为true，反之为false
     */
    public static boolean checkReceiveData(byte[] bytes, Integer protocolId) {
        String hexData = HexUtils.bytesToHex(bytes);
        int index = hexData.indexOf("68");
        // 如果头帧不为68，则数据异常
        if (index >= 0) {
            hexData = StringUtils.substring(hexData, index);
            // 获取尾帧
            String endHex = StringUtils.substring(hexData, hexData.length() - 2);
            // 如果尾帧不为16，则数据异常
            if (!StringUtils.equals("16", endHex)) return false;

            if (protocolId != null) {
                if (protocolId == 0) {
                    // 获取数据长度
                    int hexLength = Integer.parseInt(hexData.substring(6, 10), 16);
                    // 判断数据长度是否对应
                    if (hexData.length() != (hexLength * 2)) return false;
                } else if (protocolId == 1){
                    // 获取数据长度
                    int hexLength = Integer.parseInt(hexData.substring(2, 6), 16);
                    // 判断数据长度是否对应
                    if (hexData.length() != (hexLength * 2 + 2)) return false;
                }
            }
            // 判断校验和
//            String crcHex = HexUtil.crc16(HexUtil.hexToBytes(StringUtils.substring(hexData, 2, hexData.length() - 6)));
//            String crc16Str = StringUtils.substring(hexData, hexData.length() - 6, hexData.length() -2);
//            if (!StringUtils.equals(crcHex, crc16Str)) return false;

            return true;
        }
        return false;
    }

    /**
     * 组包
     * @param buf
     *      缓冲区数据
     * @param receive
     *      新接收到的数据
     * @return
     */
    public static byte[] setOfPackages(byte[] buf, byte[] receive) {
        // 如果缓冲区为空，直接返回新接收到的数据
        if (buf == null) return receive;

        byte[] result = new byte[buf.length + receive.length];
        System.arraycopy(buf, 0, result, 0, buf.length);
        System.arraycopy(receive, 0, result, buf.length, receive.length);
        return result;
    }
}
